package client;

import codec.FileRequest;
import codec.FileRespond;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import server.FileServer;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.sql.Time;

/**
 * Created by ryan on 15-8-25.
 */
public class FileClientIoHandler extends IoHandlerAdapter {
    private String fileName;
    private long startPos;
    private int length;
    private long start;

    RandomAccessFile file;
    private MappedByteBuffer mb;

    public FileClientIoHandler(String fn, long sp, int ln) {
        fileName = fn;
        startPos = sp;
        length = ln;

        try {
            file = new RandomAccessFile(fileName, "r");
            mb = file.getChannel().map(FileChannel.MapMode.READ_ONLY, start, length);
            //@To do: Test memory map speed
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void sessionCreated(IoSession session) throws Exception {

    }

    public void sessionOpened(IoSession session) throws Exception {
        start = System.nanoTime();
    }

    public void sessionClosed(IoSession session) throws Exception {
    }

    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
    }

    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {

    }

    public void messageReceived(IoSession session, Object message) throws Exception {



//        System.out.println("Received");
        FileRequest rq = (FileRequest) message;

        //System.out.println(rq.getStartPos());

        long trueOffset = startPos + rq.getStartPos();
        int valid_length = Math.min(FileClient.transmitSpeed, length);
        //System.out.println(valid_length);

        byte[] bytes = new byte[valid_length];
        file.seek(trueOffset);
        if (file.read(bytes, 0, valid_length) != valid_length) {
            System.out.println("Error!");
        }

        FileRespond frs = new FileRespond(trueOffset, valid_length, bytes, rq.getStartPos()+valid_length);
        session.write(frs);

        length -= valid_length;

        if (length == 0) {
            System.out.println("Transmit OK");
            System.out.println("Time: " + (System.nanoTime() - FileClient.startTime) / 1000000000);
            //session.close();
        }

    }


}
